package com.gk.courses.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gk.courses.dao.CourseDao;
import com.gk.courses.model.Course;
import com.gk.courses.model.Student;

@Repository
public class CourseJpaDao implements CourseDao {

	@PersistenceContext
	private EntityManager em;
	
	@Override
	public Course findById(Integer id) {
		Query query = em.createQuery("from Course c where c.courseId = :id");
		query.setParameter("id", id);
		return (Course)query.getSingleResult();
	}

	@Override
	public void save(Course course) {
		em.persist(course);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Course> findAll() {
		return em.createQuery("from Course c").getResultList();
	}

	@Override
	public List<Student> getEnrollment(Course course) {
		return course.getStudents();
	}

	@Override
	public void enrollStudentInCourse(Course course, Student student) {
		List<Student> students = course.getStudents();
		if (!students.contains(student)) {
			students.add(student);
		}
		course.setStudents(students);
		em.merge(course);
	}

	@Override
	public void updatePrerequisities(Course parentCourse, Course dependedCourse) {
		List<Course> prereq = dependedCourse.getPrerequisites();
		if ( !prereq.contains(parentCourse)) {
			prereq.add(parentCourse);
		}
		dependedCourse.setPrerequisites(prereq);
		em.merge(dependedCourse);
	}
	
}
